import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import random

# 设置随机种子以保证结果的可重复性
np.random.seed(0)

# 生成虚拟数据集
n = 100
data = {
    'Feature1': np.random.normal(50, 10, n),  # 正态分布数据
    'Feature2': np.random.normal(30, 5, n),   # 正态分布数据
}

# 创建DataFrame
df = pd.DataFrame(data)

# 在 Feature1 和 Feature2 中引入一些随机缺失值
missing_indices = random.sample(range(n), 20)
df.loc[missing_indices, 'Feature1'] = np.nan
missing_indices = random.sample(range(n), 15)
df.loc[missing_indices, 'Feature2'] = np.nan

# 创建填补前的图形
fig, axs = plt.subplots(2, 3, figsize=(18, 12), sharey=False)
fig.suptitle('Constant Imputation Analysis', fontsize=18)

# 填补前的数据分析
sns.scatterplot(x='Feature1', y='Feature2', data=df, color="blue", ax=axs[0, 0])
axs[0, 0].set_title('Scatter Plot (Before Imputation)', fontsize=14)

sns.histplot(df['Feature1'], color="purple", kde=True, ax=axs[0, 1])
axs[0, 1].set_title('Histogram of Feature1 (Before Imputation)', fontsize=14)

sns.boxplot(y='Feature1', data=df, color="orange", ax=axs[0, 2])
axs[0, 2].set_title('Box Plot of Feature1 (Before Imputation)', fontsize=14)

# 使用常数值填补
fill_value = 40
df_filled = df.fillna(fill_value)

# 填补后的数据分析
sns.scatterplot(x='Feature1', y='Feature2', data=df_filled, color="green", ax=axs[1, 0])
axs[1, 0].set_title('Scatter Plot (After Imputation)', fontsize=14)

sns.histplot(df_filled['Feature1'], color="red", kde=True, ax=axs[1, 1])
axs[1, 1].set_title('Histogram of Feature1 (After Imputation)', fontsize=14)

sns.boxplot(y='Feature1', data=df_filled, color="yellow", ax=axs[1, 2])
axs[1, 2].set_title('Box Plot of Feature1 (After Imputation)', fontsize=14)

# 显示图形
plt.tight_layout(rect=[0, 0, 1, 0.96])
plt.show()